using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.Linq;
using Spike_EBC_Designer.ViewModel;

namespace Spike_EBC_Designer
{
    public class EbcXmlExportAdapter
    {
        public static void Export(string filename, Grid grid)
        {
            var doc = new XElement("board");
            doc.Add(new XAttribute("name", grid.Label));
            if (!string.IsNullOrEmpty(grid.Implements)) doc.Add(new XAttribute("implements", grid.Implements));

            foreach (var ns in grid.Usings.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries))
                doc.Add(new XElement("using", new XAttribute("namespace", ns)));

            foreach (var rel in grid.Relations)
            {
                var wire = new XElement("wire");
                wire.Add(new XAttribute("from", BuildPinName(rel.From.Label, string.IsNullOrEmpty(rel.OutputPinName) ? "Result" : rel.OutputPinName)));
                wire.Add(new XAttribute("type", rel.Typename));
                wire.Add(new XAttribute("to", BuildPinName(rel.To.Label, string.IsNullOrEmpty(rel.InputPinName) ? "Process" : rel.InputPinName)));
                doc.Add(wire);
            }

            doc.Save(filename);
        }


        private static string BuildPinName(string nameOfFunctionalUnit, string pinName)
        {
            var fullPinName = nameOfFunctionalUnit.Replace(" ", "_");
            if (!string.IsNullOrEmpty(pinName)) fullPinName += "." + pinName.Replace(" ", "_");
            return fullPinName;
        }
    }
}